package com.doubao.file.interceptor;

import com.doubao.file.security.UserContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 用户认证拦截器，从请求头中获取用户ID
 */
@Component
@Slf4j
public class UserAuthInterceptor implements HandlerInterceptor {

    private static final String USER_ID_HEADER = "X-User-ID";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 清理上下文以确保不会有残留的用户ID
        UserContext.clear();

        // 记录所有请求头，用于调试
        log.debug("===== 请求头信息 =====");
        java.util.Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            log.debug("{}: {}", headerName, request.getHeader(headerName));
        }

        // 从网关传递的X-User-ID头获取用户ID
        String userIdStr = request.getHeader(USER_ID_HEADER);
        if (StringUtils.hasText(userIdStr)) {
            try {
                Long userId = Long.valueOf(userIdStr);
                UserContext.setUserId(userId);
                log.debug("从X-User-ID头提取用户ID: {}", userId);
            } catch (NumberFormatException e) {
                log.error("无法解析X-User-ID: {}", userIdStr, e);
            }
        }

        // 总是允许请求通过，具体接口会根据需要检查认证状态
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // 请求结束后清理上下文
        UserContext.clear();
    }
}